package common.util;

import common.TreeNode;
import lombok.experimental.UtilityClass;

import java.util.*;

/**
 * @author : wenchao.long
 * @date : Created in 2021/7/13 10:28 周二
 * @description :
 */
@UtilityClass
public class TreeNodeUtil {

    public static TreeNode newInstance(int val) {
        return new TreeNode(val);
    }

    public static TreeNode create(Integer... nums) {
        Deque<Integer> deque = new LinkedList<>(Arrays.asList(nums));
        return create(deque);
    }

    private static TreeNode create(Deque<Integer> integers) {
        TreeNode node = null;
        if (integers == null || integers.isEmpty()) {
            return null;
        }
        Integer val = integers.remove();
        if (val != null) {
            node = newInstance(val);
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(node);
        while (!integers.isEmpty()) {
            TreeNode root = deque.poll();
            Integer leftVal = integers.poll();
            Integer rightVal = integers.poll();

            TreeNode leftNode = null;
            if (leftVal != null) {
                leftNode = newInstance(leftVal);
                deque.add(leftNode);
            }

            TreeNode rightNode = null;
            if (rightVal != null) {
                rightNode = newInstance(rightVal);
                deque.add(rightNode);
            }

            if (root != null) {
                root.left = leftNode;
                root.right = rightNode;
            }
        }
        return node;
    }

    public static void levelOrderList(TreeNode root) {
        List<List<Integer>> result = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new LinkedList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                list.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            result.add(list);
        }
        System.out.println(result);
    }
}
